import env from '../config/env';
const { view, lensProp, prop, path, pipe, tap } = require('ramda');
const { chain, fold, I, map, ap } = require('pointfree-fantasy');
const request = require('superagent');
const Task = require('data.task');
const Maybe = require('data.maybe');
//引入定时服务
const schedule = require('node-schedule');
const { skip } = env;
//引入redis
import { redis } from './db';
import { ErrorHelper } from './customerrors/ErrorHelper';

//获取微信公众平台的access_token
export const makeWechatmpToken = () => new Task((rej, res) => {
    let url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential"
    let options = {
        appId: env.wechatmp.appId,
        secret: env.wechatmp.appSecret
    }
    request.get(url)
        .query(options)
        .end((err, result) => {
            if (err) {
                rej(err)
            }
            else {
                res(result.body)
            }
        })
})

export const getWechatmpTicket = (info) => new Task((rej, res) => {
    let access_token = info.access_token;
    console.log(access_token);
    let url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket"
    let options = {
        access_token: access_token,
        type: "jsapi"
    }
    request.get(url)
        .query(options)
        .end((err, result) => {
            if (err) {
                rej(err)
            } else {
                res(result.body)
            }
        })
})

//将access_token定时存入redis
export const setWechatmpToken = pipe(
    () => makeWechatmpToken(),
    chain(info => new Task((rej, res) => {
        redis.set('access_token', info.access_token).then(() => res(info)).catch(rej)
    })),
    chain(getWechatmpTicket),
    chain(info => new Task((rej, res) => {
        redis.set('jsapi_ticket', info.ticket).then(() => res(info)).catch(rej)
    })),
)

// 从redis中获取access_token
export const getWechatmpToken = (info) => new Task((rej, res) => {
    redis.get('access_token').then(access_token => {
        info.access_token = access_token
        res(info)
    }).catch(rej)
})

export const getWechatTicket = (info) => new Task((rej, res) => {
    redis.get('jsapi_ticket').then(ticket => {
        info.jsapi_ticket = ticket
        res(info)
    }).catch(rej)
})


let rule = new schedule.RecurrenceRule();
rule.minute = 0;

export const scheduleSetToken = () => {
    // if (skip.wechatMp && skip.wechatMp()) return;
    //启动的时候立即执行
    setWechatmpToken().fork(err => console.log(err), () => { });
    //启动后每小时定时执行
    schedule.scheduleJob(rule, function () {
        setWechatmpToken().fork(err => console.log(err), () => { })
    })
}
